package net.zjitc.dao.impl;

import net.zjitc.dao.CategorySecondDao;
import net.zjitc.pojo.Category;
import net.zjitc.pojo.CategorySecond;
import net.zjitc.utils.db.C3P0Utils;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.MapHandler;

import java.sql.SQLException;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2017/11/15.
 */
public class CategorySecondDaoImpl implements CategorySecondDao{
    public List<CategorySecond> findAll() {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select * from categorysecond";
        try {
            List<CategorySecond> list = (List<CategorySecond>) runner.query(sql,new BeanListHandler(CategorySecond.class));
            return list;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public int insert(CategorySecond categorySecond) {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "insert into categorysecond (csname ,cid) value(?,?)";
        try {
            int count = runner.update(sql,categorySecond.getCsname(),categorySecond.getCategory().getCid());
            return count;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }

    public CategorySecond findByCSId(String csid) {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "select * from categorysecond where csid = ?";
        try {
            /*Map将字段名和对应的值封装成一个map集合，
            csid  1
            csname 羽绒服
            cid   1
            这样使用BeanUtils可以将不同的字段赋值给不同的类*/
            Map<String,Object> map = runner.query(sql,new MapHandler(),csid);
            Category category = new Category();
            CategorySecond categorySecond = new CategorySecond();
            BeanUtils.populate(category,map);
            BeanUtils.populate(categorySecond,map);
            categorySecond.setCategory(category);
            return categorySecond;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public int update(CategorySecond categorySecond) {
        QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource());
        String sql = "update categorysecond set csname = ?,cid=? where csid=?";
        try {
            int count = runner.update(sql,categorySecond.getCsname(),categorySecond.getCategory().getCid(),categorySecond.getCsid());
            return count;

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return 0;
    }
}
